import React from 'react'
import {Row, Col, Button, Table, Select, Input, Tag} from 'antd'
// import { UserOutlined } from '@ant-design/icons';
import './styles.css'
import Detail from "./Detail"
import axios from 'axios';
import api from '../../api/api'

const {Search} = Input;
const {Option} = Select;


class VisitingRecords extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            detailHidden: true,
            data: [],
            selectCompanyId: undefined,
            selectFactoryId: undefined,
            selectDepartmentId: undefined,
            inputValue: '',
            pageNum: 1,
            pageSize: 10,
        };
    }

    componentDidMount() {
        this.getVisitingList();
        this.companyChange();
    }

    columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            className: "elementHidden",
            key: 'id',
            width: '10%'
        },
        // {
        //     title: '访问公司',
        //     dataIndex: 'company',
        //     key: 'company',
        //     width: '10%'
        // },
        {
            title: '访问公司',
            dataIndex: 'factory',
            width: '10%',
            key: 'factory'
        },
        {
            title: '部门',
            dataIndex: 'department',
            width: '10%',
            key: 'department'
        },
        {
            title: '访问人姓名',
            dataIndex: 'name',
            width: '10%',
            key: 'name'
        },
        {
            title: '手机号',
            dataIndex: 'visitMobile',
            width: '10%',
            key: 'visitMobile'
        },
        {
            title: '到访时间',
            dataIndex: 'time',
            width: '10%',
            key: 'time'
        },
        {
            title: '到访状态',
            dataIndex: 'handleType',
            className: "elementHidden",
            width: '5%',
            key: 'handleType'
        },
        {
            title: '状态',
            dataIndex: 'state',
            width: '10%',
            key: 'state',
            render: (text, record, index) => {
                //TODO 状态值
                let state = record.state;
                let stateInfo = "";
                let color = "magenta";
                if (state == "1") {
                    stateInfo = "审核中";
                    color = "geekblue";
                } else if (state == "2") {
                    if (record.handleType == "0") {
                        stateInfo = "已通过,未到访";
                        color = "green";
                    } else if (record.handleType == "1") {
                        stateInfo = "已到访,未出厂";
                        color = "green";
                    } else {
                        stateInfo = "结束到访";
                        color = "green";
                    }
                } else if (state == "3") {
                    stateInfo = "已驳回";
                    color = "volcano";
                }
                return (
                    <div>
                        <Tag color={color}>{stateInfo}</Tag>
                    </div>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '15%',
            key: 'option',
            render: (text, record, index) => {
                return (
                    <span>
            <a className="optionMargin" onClick={() => this.onClickDetail(record)}>查看详情</a>
          </span>
                )
            }
        }
    ];

    //分页操作
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getVisitingList()
        });
    }

    getVisitingList() {
        var that = this;
        axios.post(api.api_URL + "/admin/visitrecord/queryAllVisitApplyRecordByParam", {
            "pageNum": this.state.pageNum,
            "pageSize": this.state.pageSize,
            "gsThirdId": that.state.selectCompanyId,
            "cqThirdId": that.state.selectFactoryId,
            "bmThirdId": that.state.selectDepartmentId,
            "name": this.state.inputValue,
            "orgCode":localStorage.getItem('orgCode')
        }, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            console.log(res.data)
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            const dataList = [];
            let total = res.data.data.list.totalSize;
            for (let i = 0; i < res.data.data.list.content.length; i++) {
                let resContent = res.data.data.list.content[i];

                const content = {};
                content.key = (i + 1);
                content.id = resContent.id;
                content.company = resContent.companyName;
                content.factory = resContent.factoryName;
                content.department = resContent.deptName;
                content.name = resContent.visitName;
                content.phoneNum = resContent.mobile;
                content.visitMobile = resContent.visitMobile;
                content.time = resContent.visitTime;
                content.state = resContent.type;
                content.handleType = resContent.handleType;
                dataList[i] = content;
            }
            that.setState({
                total: total,
                data: dataList
            })
        }).catch(function (err) {
            console.log(err);
        });
    }

    // 获取子组件
    onRef(name, ref) {
        switch (name) {
            case 'visitDetail':
                this.detail = ref
                break
        }
    }

    //查看详情
    onClickDetail(item) {
        console.info("查看详情===", item);
        this.setState({
            detailHidden: false
        })
        this.detail.getVisitApplyInfo(item.id);
        this.detail.getVisitPartnerInfoList(item.id)
    }

    returnMain = e => {
        this.setState({
            detailHidden: true
        })
    }

    onclickSearch() {
        console.info("搜索");
        this.getVisitingList();
    }

    onclickReset() {
        this.departmentSelect=[];
        console.info("重置");
        this.setState({
            selectCompanyId:undefined,
            selectFactoryId: undefined,
            selectDepartmentId: undefined,
            inputValue:'',
        },() => {
            this.getVisitingList()
        });
        console.log(this.props)
    };

    //获取公司下拉框值
    companySelect = [];

    getCompanySelect() {
        let that = this;
        let dataList = [];
        let url = api.api_URL + "/admin/company/queryAllCompanyInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let companyInfoList = res.data.data.companyInfoList;
            for (let i = 0; i < companyInfoList.length; i++) {
                let comData = companyInfoList[i];
                const data = {};
                data.key = comData.thirdCompanyId;
                data.label = comData.companyName;
                dataList[i] = data;
            }
            for (let i = 0; i < dataList.length; i++) {
                that.companySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }
        }).catch(function (err) {
            console.log(err);
        })

    }

    //获取厂区下拉框值
    factorySelect = [];

    //选择公司
    companyChange = () => {
        this.factorySelect = [];
        this.departmentSelect = [];
        let that = this;
        let dataList = [];
        let url;
        url = api.api_URL + "/admin/factory/queryFactoryInfoForSelect?orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let factoryInfoList = res.data.data.factoryInfoList;
            if (factoryInfoList.length <= 0) {
                console.log("没有厂房数据")
                return;
            }
            for (let i = 0; i < factoryInfoList.length; i++) {
                let facData = factoryInfoList[i];
                const data = {};
                data.key = facData.thirdFactoryId;
                data.label = facData.name;
                console.log(data)
                dataList[i] = data;
            }
            console.log(("companyChange:" + dataList))
            for (let i = 0; i < dataList.length; i++) {
                that.factorySelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }
        }).catch(function (err) {
            console.log(err);
        })
    }

    //获取部门下拉框值
    departmentSelect = [];

    //选择厂区
    factoryChange = (value) => {
        this.setState({
            selectFactoryId: value
        })
        this.departmentSelect = [];
        let that = this;
        let dataList = [];
        let url = api.api_URL + "/admin/dept/queryAllDepartmentInfoByThirdFactoryIdForSelect?thirdFactoryId=" + value + "&orgCode=" + localStorage.getItem('orgCode');
        axios.get(url, {
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": api.ContentType
            }
        }).then(function (res) {
            if (res.data.code != 1) {
                alert(res.data.msg);
                return;
            }
            let departmentInfoList = res.data.data.departmentInfoList;
            if (departmentInfoList.length <= 0) {
                console.log("没有部门数据")
                return;
            }
            for (let i = 0; i < departmentInfoList.length; i++) {
                let comData = departmentInfoList[i];
                const data = {};
                data.key = comData.thirdDepartmentId;
                data.label = comData.name;
                console.log(data)
                dataList[i] = data;
            }
            console.log(("factoryChange:" + dataList))
            for (let i = 0; i < dataList.length; i++) {
                that.departmentSelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
            }
        }).catch(function (err) {
            console.log(err);
        })
    }

    departmentSearch = (searchKey) =>{
        console.log('search:', searchKey);
        // let that = this;
        // let dataList = [];
        // let url = api.api_URL + "/admin/dept/queryAllDepartmentInfoByThirdFactoryIdForSelect?thirdFactoryId=" + this.state.selectFactoryId + "&orgCode=" + localStorage.getItem('orgCode')+"&searchKey=" + searchKey;
        // axios.get(url, {
        //     headers: {
        //         "Authorization": localStorage.getItem('token'),
        //         "Content-Type": api.ContentType
        //     }
        // }).then(function (res) {
        //     if (res.data.code != 1) {
        //         alert(res.data.msg);
        //         return;
        //     }
        //     let departmentInfoList = res.data.data.departmentInfoList;
        //     if (departmentInfoList.length <= 0) {
        //         console.log("没有部门数据")
        //         return;
        //     }
        //     for (let i = 0; i < departmentInfoList.length; i++) {
        //         let comData = departmentInfoList[i];
        //         const data = {};
        //         data.key = comData.thirdDepartmentId;
        //         data.label = comData.name;
        //         console.log(data)
        //         dataList[i] = data;
        //     }
        //     console.log(("departmentSearch:" + dataList))
        //     that.departmentSelect = [];
        //     for (let i = 0; i < dataList.length; i++) {
        //         that.departmentSelect.push(<Option key={dataList[i].key}>{dataList[i].label}</Option>);
        //     }
        // }).catch(function (err) {
        //     console.log(err);
        // })
    }

    departmentChange = (value) => {
        this.setState({
            selectDepartmentId: value
        })
    }

    inputChange = (e) => {
        this.setState({
            inputValue: e.target.value
        })
    }

    downloadClick = () => {
        let that = this;
        let exportUrl = api.api_URL + "/admin/visitrecord/downVisitRecordExcel";
        let data = {
            "gsThirdId": that.state.selectCompanyId,
            "bmThirdId": that.state.selectFactoryId,
            "cqThirdId": that.state.selectDepartmentId,
            "name": that.state.inputValue,
            "orgCode": localStorage.getItem("orgCode")
        }
        that.exportFile(exportUrl, data)
    }

    exportFile(url, data) {
        axios({
            method: 'post',
            url: url,
            data: data,
            responseType: 'blob'
        }).then((res) => {
            const content = res.data;
            const blob = new Blob([content]);
            const fileName = "访问导出数据.xls";
            const selfURL = window[window.webkitURL ? 'webkitURL' : 'URL'];
            let elink = document.createElement('a');
            if ('download' in elink) {
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = selfURL['createObjectURL'](blob);
                document.body.appendChild(elink);

                // 触发链接
                elink.click();
                selfURL.revokeObjectURL(elink.href);
                document.body.removeChild(elink)
            } else {
                navigator.msSaveBlob(blob, fileName);
            }
        })
    }

    render() {

        return (
            <div className="girdBg">
                <div className={this.state.detailHidden === true ? "elementShow" : "elementHidden"}>
                    <Row className="searchBox">
                        <Col span={20}>
                            {/*<Select placeholder="请选择公司" style={{width: 250}} onChange={this.companyChange}  allowClear  value={this.state.selectCompanyId}>*/}
                                {/*{this.companySelect}*/}
                            {/*</Select>*/}
                            <Select showSearch={true} optionFilterProp="children" placeholder="请选择公司" style={{width: 250, marginLeft: 30}}  allowClear value={this.state.selectFactoryId}
                                    onChange={this.factoryChange}  allowClear >
                                {this.factorySelect}
                            </Select>
                            <Select showSearch={true} optionFilterProp="children" placeholder="请选择部门" style={{width: 250, marginLeft: 30}}  allowClear value={this.state.selectDepartmentId}
                                    onChange={this.departmentChange}  allowClear>
                                {this.departmentSelect}
                            </Select>
                            <Search style={{width: 250, marginLeft: 30}}
                                    placeholder="请输入姓名" onChange={this.inputChange}  allowClear  value={this.state.inputValue}
                            />
                            <Button icon={"search"} type='primary' style={{marginLeft: 30}}
                                    onClick={this.onclickSearch.bind(this)}>搜索</Button>
                            <Button style={{marginLeft: 30}}
                                    onClick={this.onclickReset.bind(this)}>重置</Button>
                        </Col>
                        <Col span={4} className="btnRight">
                            <Button shape='circle' type='primary' icon="download" onClick={this.downloadClick}/>
                        </Col>
                    </Row>
                    <Row style={{margin: 30}}>
                        <Table
                            columns={this.columns}
                            dataSource={this.state.data}
                            scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                            columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                                const fun = () => ({style: {whiteSpace: 'nowrap'}});
                                item.onHeaderCell = fun;
                                item.onCell = fun;
                                return item;
                            })}
                            pagination={{
                                simple: false,
                                current: this.state.pageNum,
                                total: this.state.total,
                                pageSize: this.state.pageSize,
                                showTotal: (count = this.state.total) => {
                                    return '共' + count + '条'
                                },
                                onChange: (current, pageSize) => {
                                    this.onBaseClick(current, pageSize)
                                }
                            }}
                        />
                    </Row>
                </div>
                <div className={this.state.detailHidden === true ? "elementHidden" : "elementShow"}>
                    <Detail returnMain={this.returnMain} onRef={this.onRef.bind(this)}/>
                </div>
            </div>
        )
    }
}

export default VisitingRecords